package com.xlserver.controller;

import cn.hutool.http.server.HttpServerRequest;
import cn.hutool.http.server.HttpServerResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xlserver.dao.ConsultationMapper;
import com.xlserver.dao.StateMapper;
import com.xlserver.domain.Consultation;
import com.xlserver.domain.Counselor;
import com.xlserver.domain.State;
import com.xlserver.domain.User;
import com.xlserver.service.MessageService;
import com.xlserver.service.UserService;
import com.xlserver.util.Base64ToMultipartFile;
import com.xlserver.util.ImageParser;
import com.xlserver.util.SMSUtils;
import com.xlserver.util.model.UserInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@AllArgsConstructor
@Api(value = "登录注册相关模块接口", tags = "登录注册相关模块接口")
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    public SMSUtils smsUtils;

    @Autowired
    public ImageParser parser;

    @Autowired
    public ImageParser imageParser;

    @Autowired
    public MessageService messageService;

    @Autowired
    public ConsultationMapper consultationMapper;

    @Autowired
    public StateMapper stateMapper;

    //可以考虑加入时间戳
    private final Map<String,String> identificationCodes = new HashMap<>();

    /**
     * 密码登录
     * @return 1.无user 2.密码错误 3.成功 4.被封禁
     */
    @PostMapping("/login")
    @ApiOperation(value = "密码登录", notes = "{username:username,password:password}")
    public Map<String, Object> login(@RequestBody Map<String, String> info){
        String phoneNum = info.get("phoneNum");
        String password = info.get("password");
        return userService.getUserInfo(phoneNum,password);
    }

    /**
     *发送验证码
     */
    @PostMapping("/code")
    @ApiOperation(value = "发送验证码", notes = "{phoneNumber:phoneNumber}")
    public JSONObject sendMsg(@RequestBody Map<String,String> info) {
        String phone = info.get("phoneNumber");
        String code = ""+(int)((Math.random()*9+1)*100000);
        identificationCodes.put(phone,code);
        smsUtils.sendMsg(phone, code);
        JSONObject ret = new JSONObject();
        ret.put("result","success");
        return ret;
    }

    /**
     *验证码登录
     */
    @PostMapping("/loginByCode")
    @ApiOperation(value = "验证码登录", notes = "{phoneNum:phoneNum,code:code}")
    public Map<String, Object> loginByCode(@RequestBody Map<String, String> info){
        //验证码登录在测试阶段先去掉
//        identificationCodes.put(info.get("phoneNum"),info.get("code"));
        String code = info.get("code");
        String phoneNum = info.get("phoneNum");
        if (judgeCode(code,info.get("phoneNum"))){
            return JSONObject.parseObject(
                    JSON.toJSON(userService.getUserInfoByCode(phoneNum, code)).toString());
        }
        else {//验证码错误
            JSONObject ret = new JSONObject();
            ret.put("result","2");
            return ret;
        }
    }
    /**
     * 获取个人咨询记录
     */
    @PostMapping("/getHistory")
    public JSONArray getHistory(@RequestBody Map<String,String> info){
        int id = Integer.parseInt(info.get("id"));
        return messageService.getUserHistory(id);
    }

    /**
     *获取详细消息记录
     */
    @PostMapping("getMessages")
    public JSONArray getMessages(@RequestBody Map<String,String> info){
        int hid = Integer.parseInt(info.get("hid"));
        return messageService.getMsgsOfChat(hid);
    }

    /**
     *注册
     */
    @PostMapping("/register")
    @ApiOperation(value = "注册", notes = "userInfo")
    public JSONObject register(@ModelAttribute UserInfo userInfo) {
        //测试时不使用验证码
//        identificationCodes.put(userInfo.getPhoneNum(),userInfo.getCode());
        System.out.println(userInfo+"===");
        String code = userInfo.getCode();
        String phoneNum = userInfo.getPhoneNum();
        if (code.equals(identificationCodes.get(phoneNum)) && !userService.checkPhoneNum(phoneNum)){
            JSONObject ret = JSONObject.parseObject(
                    JSON.toJSON(userService.register(userInfo)).toString());
            ret.put("result","success");
            return ret;
        }
        else if(!code.equals(identificationCodes.get(phoneNum))){
            JSONObject ret = new JSONObject();
            ret.put("result","code");
            return ret;
        }
        else{
            JSONObject ret = new JSONObject();
            ret.put("result","phoneNum");
            return ret;
        }
    }

    /**
     *更新信息
     */
    @PostMapping("/updateInfo")
    @ApiOperation(value = "更新信息", notes = "userInfo,uid为当前用户id")
    public JSONObject updateUserInfo(@RequestBody Map<String,String> info){
        return userService.updateUser(info);
    }

    /**
     *更新密码
     */
    @PostMapping("/updatePassword")
    @ApiOperation(value = "更新密码", notes = "{phoneNum:phoneNum,code:code,userId:userId,password:password}")
    public JSONObject updatePassword(@RequestBody Map<String,String> info){
        //验证码登录在测试阶段先去掉
        identificationCodes.put(info.get("phoneNum"),info.get("code"));
        String code = info.get("code");
        String phoneNum = info.get("phoneNum");
        String id = info.get("userId");
        String password = info.get("password");
        if (judgeCode(code,phoneNum)){
            return userService.updatePassword(id,password);
        }
        else {
            JSONObject ret = new JSONObject();
            ret.put("res","failure");
            return ret;
        }
    }
    /**
     * 更新头像
     */
    @PostMapping("/updateAvatar")
    public JSONObject updateAvatar(@RequestBody Map<String, String> info) throws IOException {
        String data = info.get("uploadFile");
        String id = info.get("id");
        data = ImageParser.saveImage(convertBaseToMultipartFile(data));
        return userService.updateAvatar(data,Integer.parseInt(id));
    }

    /**
     *确认验证码
     */
    @ApiOperation(value = "确认验证码", notes = "{code:code,phoneNum:phoneNum}")
    private boolean judgeCode(String code, String phoneNum){
        return code.equals(identificationCodes.get(phoneNum));
    }

    /**
     *base64格式转为multipartfile格式
     */
    private MultipartFile convertBaseToMultipartFile(String base64){
        final String[] base64Array = base64.split(",");
        String dataUir, data;
        if (base64Array.length > 1) {
            dataUir = base64Array[0];
            data = base64Array[1];
        } else {
            //根据你base64代表的具体文件构建
            dataUir = "data:image/jpg;base64";
            data = base64Array[0];
        }
        return new Base64ToMultipartFile(data, dataUir);
    }
    /**
     * 当前排队人数
     */
    @PostMapping("sumOfQueue")
    public JSONObject waitQueue(@RequestBody Map<String,String> info){
        int cid = Integer.parseInt(info.get("id"));
        JSONObject ret = new JSONObject();
        int sum = Math.toIntExact(consultationMapper.selectCount(new QueryWrapper<Consultation>()
                .eq("cid", cid)
                .apply("h_beginTime = h_endTime")));
        int state = stateMapper.selectOne(new QueryWrapper<State>().eq("id",cid)).getState();
        //忙碌
        if (state == 1){
            sum--;
        }
        ret.put("sum",sum);
        return ret;
    }
    /**
     * 用户评价咨询师
     */
    @PostMapping("comment")
    public JSONObject commendCounselor(@RequestBody Map<String,String> info){
        int cid = Integer.parseInt(info.get("cid"));
        int uid = Integer.parseInt(info.get("uid"));
        double rank = Double.parseDouble(info.get("rank"));
        return userService.commend(uid,cid,rank);
    }
    /**
     * 通过hid查看获取咨询师姓名与会话时间
     */
    @PostMapping("getMsgsById")
    public JSONObject getMsgsById(@RequestBody Map<String,String> info) throws ParseException {
        int hid = Integer.parseInt(info.get("hid"));
        return messageService.getInfoByHid(hid);
    }

}
